package es.udc.emarketapp.emarket.model.purchase.dao;

import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;

import es.udc.fbellas.j2ee.util.exceptions.InternalErrorException;
import es.udc.fbellas.j2ee.util.sql.GeneralOperations;
import es.udc.emarketapp.emarket.model.purchase.vo.PurchaseVO;
import java.sql.Timestamp;
import java.util.Calendar;


// An implementation of <code>SQLPurchaseDAO</code> for databases providing
// counter columns with JDBC 3 drivers.
 

public class MySQLPurchaseDAO extends AbstractSQLPurchaseDAO {

    public PurchaseVO create(Connection connection, PurchaseVO purchaseVO)
        throws InternalErrorException {
        
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
    
        try {
                
            // Create "preparedStatement". 
            String queryString = "INSERT INTO compra" +
                "(id_comprador, fecha, valor, forma_pago)" +
                "VALUES (?, ?, ?, ?)";
        
            preparedStatement = connection.prepareStatement(queryString,
                Statement.RETURN_GENERATED_KEYS);    
            
            // Fill "preparedStatement". 
            int i = 1;
            preparedStatement.setString(i++, purchaseVO.getIdComprador());
            preparedStatement.setTimestamp(i++,
                    new Timestamp(Calendar.getInstance().getTime().getTime()));
            preparedStatement.setDouble(i++, purchaseVO.getValor());
            preparedStatement.setString(i++, purchaseVO.getFormaPago());
                        
            // Execute query.
            int insertedRows = preparedStatement.executeUpdate();
        
            if (insertedRows == 0) {
                throw new SQLException("No se pudo insertar la fila a la tabla" +
                    " 'Compra'");
            }

            if (insertedRows > 1) {
                throw new SQLException("Fila duplicada en la tabla 'Compra'");
            }
            
            // Get account identifier. 
            resultSet = preparedStatement.getGeneratedKeys();

            if (!resultSet.next()) {
                throw new InternalErrorException(new SQLException(
                    "el driver JDBC no ha devuelto el identificador generado"));
            }

            Long nCompra = new Long(resultSet.getLong(1));
            
            // Return the value object. 
            return new PurchaseVO(nCompra.longValue(),
                    purchaseVO.getIdComprador(), purchaseVO.getFecha(),
                    purchaseVO.getValor(), purchaseVO.getFormaPago());
            
        
        } catch (SQLException e) {
            throw new InternalErrorException(e);
        } finally {
            GeneralOperations.closeStatement(preparedStatement);
        }
        
    }


}